package com.dwxt.common.exception;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.DateUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;

@ControllerAdvice
@Slf4j
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public BaseResult handle(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        String requestURI = request.getRequestURI();
        String dataStr = DateUtils.formatTime(new Date());
        if (exception instanceof ExpiredJwtException) {
            return BaseResult.build(StatusCode.PERMISSION_FAIL);
        }
        log.error("{}====={}", dataStr, requestURI, exception);
        response.setStatus(SC_INTERNAL_SERVER_ERROR);
        return BaseResult.build(StatusCode.FAIL);
    }
}
